//
//  RYAddDizhiViewController.swift
//  SheYangBigData
//
//  Created by 宋海胜 on 2021/1/14.
//  Copyright © 2021 叁拾叁. All rights reserved.
//



import UIKit
import IQKeyboardManagerSwift

enum EditType {
    case add
    case edit
}

class RYAddDizhiViewController: SYBaseViewController, UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate {
    
    
    var tableView: UITableView!
    var type: EditType = .add
    var params: [String: String] = [:]
    var areaParams: [String: String] = [:]
    
    var selectAreaDefault: String = "请选择"
    var selectArea: [String] = ["请选择", "", "", ""]
    
    var choiceDatas: [[String: String]] = [[String: String]]()
    
    var choiceSecDatas: [[String: String]] = [[String: String]]()
    
    var choiceThirDatas: [[String: String]] = [[String: String]]()
    
    var choiceFourDatas: [[String: String]] = [[String: String]]()
    
    var addressChoiceView: RYAddressChoiceView = RYAddressChoiceView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.enable = true
        IQKeyboardManager.shared.enableAutoToolbar = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared.enable = false
        IQKeyboardManager.shared.enableAutoToolbar = false
    }
    
    init(type: EditType = .add, model: RYAddressListModel? = nil) {
        super.init(nibName: nil, bundle: nil)
        self.type = type
        
        if type == .edit {
            self.params = ["name": model?.name ?? "",
                           "id": model?.id ?? "",
                           "appUserId": "\(model?.appUserId ?? 0)",
                           "isDefault": "\(model?.isDefault ?? 0)",
                           "mobile": model?.mobile ?? "",
                           "provinceName": model?.provinceName ?? "",
                           
                           "cityName": model?.cityName ?? "",
                           "districtName": model?.districtName ?? "",
                           "streetName": model?.streetName ?? "",
                           "provinceId":model?.provinceId ?? "",
                           "cityId": model?.cityId ?? "",
                           
                           "districtId": model?.districtId ?? "",
                           "streetId": model?.streetId ?? "",
                           "address": model?.address ?? ""
            ]
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setTableView()
        self.title = "收货地址"
        setSearchView()
        setAddressView()
    }
    
    func paramsIsEmpty() -> Bool {
        if let v = self.params["name"] {
            if v.isEmpty {
                self.sy_toast("请填写收货人")
                return true
            }
        } else {
            self.sy_toast("请填写收货人")
            return true
        }
        if let v = self.params["mobile"] {
            if v.isEmpty {
                self.sy_toast("请填写收货人电话")
                return true
            }
            if !v.checkIsMobileNum() {
                self.sy_toast("请填写正确手机号")
                return true
            }
        } else {
            self.sy_toast("请填写收货人电话")
            return true
        }
        if let v = self.params["provinceName"] {
            if v.isEmpty {
                self.sy_toast("请填写所在地区")
                return true
            }
        } else {
            self.sy_toast("请填写所在地区")
            return true
        }
       
        
        if let v = self.params["address"] {
            if v.isEmpty {
                self.sy_toast("请填写详细地址")
                return true
            }
        } else {
            self.sy_toast("请填写详细地址")
            return true
        }
        return false
    }
    
    /*
     {
     "appUserId":22,
     "name":"范文涛",
     "mobile":"17867817454",
     "isDefault":0
     "provinceName":"江苏省",
     "cityName":"南京市",
     "districtName":"江宁区",
     "streetName":"禄口街道",
     "address":"",
     "provinceId":20942094041088,
     "cityId":20969856139264,
     "districtId":20971449974784,
     "streetId":20971768741888,
     }
     */
    func addData(_ dic: [String: String]) {
        if paramsIsEmpty() {
            return
        }
        requestVM.baseRequest(disposeBag: dispose, type: .addAddress(dic: dic), modelClass: SGBaseModel<RYAddressListModel>.self) {[weak self] (res) in
            if let `self` = self {
                self.popVC()
            }
            
        } Error: {
            
        }
        
    }
    
    /*
     {
     "id"
     "appUserId":22,
     "name":"范文涛",
     "mobile":"17867817454",
     "isDefault":0
     "provinceName":"江苏省",
     "cityName":"南京市",
     "districtName":"江宁区",
     "streetName":"禄口街道",
     "address":"",
     "provinceId":20942094041088,
     "cityId":20969856139264,
     "districtId":20971449974784,
     "streetId":20971768741888,
     }
     */
    func editData(_ dic: [String: String]) {
        if paramsIsEmpty() {
            return
        }
        requestVM.baseRequest(disposeBag: dispose, type: .editAddress(dic: dic), modelClass: SGBaseNoPageListModel<RYKuaidiModel>.self) {[weak self] (res) in
            if let `self` = self {
                self.popVC()
                self.backClosure?(0)
            }
            
        } Error: {
            
        }
        
    }
    
    func getAreaChoiceData(pid : Int = 0, index: Int = 0) {
        
        if index == 0 {
            self.selectArea = [selectAreaDefault, "", "", ""]
        }
        //        if index == 3 , choiceFourDatas.count != 0{
        //
        //            self.addressChoiceView.configureView(datas: self.choiceFourDatas, cengji: 3, selectArea: self.selectArea)
        //            return
        //        }else   if index == 2 , choiceThirDatas.count != 0{
        //
        //            self.addressChoiceView.configureView(datas: self.choiceThirDatas, cengji: 2, selectArea: self.selectArea)
        //            return
        //        } else if index == 1 , choiceSecDatas.count != 0{
        //
        //            self.addressChoiceView.configureView(datas: self.choiceSecDatas, cengji: 1, selectArea: self.selectArea)
        //            return
        //        } else if index == 0 , choiceDatas.count != 0 {
        //
        //            self.addressChoiceView.configureView(datas: self.choiceDatas, cengji: 0, selectArea: self.selectArea)
        //            return
        //        }
        
        requestVM.baseRequest(disposeBag: dispose, type: .diqu(pid: pid), modelClass: SGBaseNoPageListModel<RYAreaModel>.self) {[weak self] (res) in
            if let `self` = self {
                let models:[RYAreaModel] = res.data ?? []
                if index == 3 {
                    
                    self.choiceThirDatas.removeAll()
                    
                    
                    for (_, value) in models.enumerated() {
                        self.choiceFourDatas.append(["name": value.name ?? "", "id": value.id ?? ""])
                    }
                    self.addressChoiceView.configureView(datas: self.choiceFourDatas, cengji: 3, selectArea: self.selectArea)
                }else   if index == 2 {
                    
                    self.choiceThirDatas.removeAll()
                    
                    
                    for (_, value) in models.enumerated() {
                        self.choiceThirDatas.append(["name": value.name ?? "", "id": value.id ?? ""])
                    }
                    self.addressChoiceView.configureView(datas: self.choiceThirDatas, cengji: 2, selectArea: self.selectArea)
                } else if index == 1 {
                    
                    self.choiceSecDatas.removeAll()
                    
                    
                    for (_, value) in models.enumerated() {
                        self.choiceSecDatas.append(["name": value.name ?? "", "id": value.id ?? ""])
                    }
                    self.addressChoiceView.configureView(datas: self.choiceSecDatas, cengji: 1, selectArea: self.selectArea)
                    
                } else {
                    
                    self.choiceDatas.removeAll()
                    
                    for (_, value) in models.enumerated() {
                        self.choiceDatas.append(["name": value.name ?? "", "id": value.id ?? ""])
                    }
                    self.addressChoiceView.configureView(datas: self.choiceDatas, cengji: 0, selectArea: self.selectArea)
                }
                
            }
            
        } Error: {
            
        }
    }
    
    func setAddressView() {
        
        addressChoiceView.selectBiaoqianClosure = {[weak self] index in
            if let `self` = self {
                
            }
        }
        
        addressChoiceView.fir.selectClosure = {[weak self] (id, name,  index) in
            if let `self` = self {
                self.areaParams["provinceName"] = name
                self.areaParams["provinceId"] = id
                
                self.selectArea[0] = name
                self.selectArea[1] = self.selectAreaDefault
                
                self.getAreaChoiceData(pid: Int(id) ?? 0, index: index)
            }
        }
        addressChoiceView.sec.selectClosure = {[weak self] (id, name, index) in
            if let `self` = self {
                self.areaParams["cityName"] = name
                self.areaParams["cityId"] = id
                
                
                self.selectArea[1] = name
                self.selectArea[2] = self.selectAreaDefault
                
                self.getAreaChoiceData(pid: Int(id) ?? 0, index: index)
            }
        }
        addressChoiceView.thir.selectClosure = {[weak self] (id, name, index) in
            if let `self` = self {
                self.areaParams["districtName"] = name
                self.areaParams["districtId"] = id
                
                
                self.selectArea[2] = name
                self.selectArea[3] = self.selectAreaDefault
                
                self.getAreaChoiceData(pid: Int(id) ?? 0, index: index)
            }
        }
        addressChoiceView.four.selectClosure = {[weak self] (id, name, index) in
            if let `self` = self {
                self.areaParams["streetName"] = name
                self.areaParams["streetId"] = id
                self.selectArea[3] = name
                
                self.areaParams.forEach { self.params[$0] = $1 } // mark 将字典合并
                
                let cell: RYAddDizhiChoiceCell = self.tableView.cellForRow(at: IndexPath(row: 2, section: 0)) as! RYAddDizhiChoiceCell
                cell.content.text = self.selectArea.joined(separator: ",")
                cell.content.textColor = UIColor(hex: 0x333333)
                self.getAreaChoiceData(pid: Int(id) ?? 0, index: index)
            }
        }
    }
    
    
    func setTableView() {
        
        //创建表格视图
        self.tableView = UITableView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-BOTTOM_SAFE_HEIGHT), style:.plain)
        self.tableView.separatorStyle = .none
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView!.register(RYAddDizhiCell.self, forCellReuseIdentifier: "RYAddDizhiCell")
        self.tableView!.register(RYAddDizhiChoiceCell.self, forCellReuseIdentifier: "RYAddDizhiChoiceCell")
        self.tableView!.register(RYAddDizhiDetailCell.self, forCellReuseIdentifier: "RYAddDizhiDetailCell")
        
        
        self.tableView.backgroundColor = Constant.bgViewColor
        self.view.addSubview(self.tableView!)
    }
    
    func setSearchView() {
        
        let zixun: UIButton = UIButton()
        zixun.addAction {[weak self] in
            if let `self` = self {
                self.params["appUserId"] = SYUserInfo.strand.userId
                self.params["isDefault"] = "0"
                if self.type == .add {
                    
                    self.addData(self.params)
                } else {
                    self.editData(self.params)
                }
            }
        }
        
        zixun.backgroundColor = UIColor(hex: 0x367FF6)
        zixun.setTitle("保存", for: .normal)
        zixun.setTitleColor(UIColor.white, for: .normal)
        zixun.titleLabel?.font = 18.autoFontSize()
        zixun.layer.cornerRadius = 5
        view.addSubview(zixun)
        zixun.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(348.autoWidth() + NAV_HEIGHT)
            make.left.equalToSuperview().offset(15.autoWidth())
            make.right.equalToSuperview().offset(-15.autoWidth())
            make.height.equalTo(44.autoWidth())
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 3 {
            let cell: RYAddDizhiDetailCell? = tableView.dequeueReusableCell(withIdentifier: "RYAddDizhiDetailCell") as? RYAddDizhiDetailCell
            cell?.selectionStyle = .none
            
            cell!.currentVC = self
            if self.type == .edit {
                
                cell?.textView.text = self.params["address"]
            }
            cell?.inputClosure = {[weak self] text in
                if let `self` = self {
                    self.params["address"] = text
                }
            }
            return cell!
        } else if indexPath.row == 2 {
            let cell: RYAddDizhiChoiceCell? = tableView.dequeueReusableCell(withIdentifier: "RYAddDizhiChoiceCell") as? RYAddDizhiChoiceCell
            cell?.selectionStyle = .none
            cell!.currentVC = self
            if self.type == .edit {
                let pn: String = self.params["provinceName"] ?? ""
                let cn: String  = self.params["cityName"] ?? ""
                let dn : String = self.params["districtName"] ?? ""
                let sn : String = self.params["streetName"] ?? ""
                cell?.content.text = String(format: "%@%@%@%@", pn, cn, dn, sn)
                cell?.content.textColor = UIColor(hex: 0x333333)
            }
            return cell!
        } else {
            
            let cell: RYAddDizhiCell? = tableView.dequeueReusableCell(withIdentifier: "RYAddDizhiCell") as? RYAddDizhiCell
            cell?.selectionStyle = .none
            cell!.currentVC = self
            if indexPath.row == 0 {
                cell?.title.text = "收货人"
                cell?.content.placeholder = "请输入姓名"
                if self.type == .edit {
                    cell?.content.text = self.params["name"]
                }
                cell?.inputClosure = {[weak self] text in
                    if let `self` = self {
                        self.params["name"] = text
                    }
                }
            } else {
                
                cell?.title.text = "收货人电话"
                cell?.content.placeholder = "请输入联系方式"
                if self.type == .edit {
                    cell?.content.text = self.params["mobile"]
                }
                cell?.inputClosure = {[weak self] text in
                    if let `self` = self {
                        self.params["mobile"] = text
                    }
                }
            }
            
            return cell!
        }
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let firCell: RYAddDizhiCell = tableView.cellForRow(at: IndexPath(row: 0, section: 0)) as! RYAddDizhiCell
        let secCell: RYAddDizhiCell = tableView.cellForRow(at: IndexPath(row: 1, section: 0)) as! RYAddDizhiCell
        let thirCell: RYAddDizhiDetailCell = tableView.cellForRow(at: IndexPath(row: 3, section: 0)) as! RYAddDizhiDetailCell
        if indexPath.row == 2 {
            //            choiceAddress()
            firCell.content.resignFirstResponder()
            secCell.content.resignFirstResponder()
            thirCell.textView.resignFirstResponder()
            self.getAreaChoiceData()
            self.addressChoiceView.show()
        }
    }
    
    //    func choiceAddress() {
    //        let pick = BRAddressPickerView()
    //        pick.pickerMode = .area
    //        pick.title = "请选择地区"
    //        pick.selectIndexs = [10, 0, 4]
    //        pick.isAutoSelect = true
    //        pick.resultBlock = {[weak self]  (province, city, area) in
    //
    //            if let `self` = self {
    //                self.params["provinceName"] = province?.name ?? ""
    //                self.params["cityName"] = city?.name ?? ""
    //                self.params["districtName"] = area?.name ?? ""
    //                self.params["streetName"] = area?.name ?? ""
    //            }
    //            print("\(province?.name)\n\(city?.name)\n\(area?.name)")
    //        }
    //        pick.show()
    //    }
    
}
